package com.example.bes014.web.demo.controller;

import com.example.bes014.web.demo.vo.BesInfoVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.List;

@RestController
public class MBeanDataController {

    @GetMapping(value = "/indicators")
    public BesInfoVO testGetMbean() throws MalformedObjectNameException, ReflectionException, AttributeNotFoundException, InstanceNotFoundException, MBeanException {

        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName objectName = new ObjectName("BES:type=Engine");
        String[] arr = new String[]{"serverVersion", "patchVersion"};
        AttributeList attributes = beanServer.getAttributes(objectName, arr);
        List<Attribute> list = attributes.asList();
        for (Attribute attribute : list) {
            String name = attribute.getName();
            Object value = attribute.getValue();
            System.out.println("属性名：" + name + "，属性值：" + value);
        }


        // 获取 MBeanServer
        MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
        // 构造 Engine 的 ObjectName
        ObjectName engineObjectName = new ObjectName("BES:type=Engine");
        // 获取 Engine 的 serverVersion 属性值
        String serverVersion = (String) mBeanServer.getAttribute(engineObjectName, "serverVersion");
        // 打印 serverVersion 属性值
        System.out.println("服务器版本：" + serverVersion);
        // 获取 Engine 的 patchVersion 属性值
        String patchVersion = (String) mBeanServer.getAttribute(engineObjectName, "patchVersion");
        // 打印 patchVersion 属性值
        System.out.println("补丁版本：" + patchVersion);

        BesInfoVO besInfoVO = new BesInfoVO();
        besInfoVO.setServerVersion(serverVersion);
        besInfoVO.setPatchVersion(patchVersion);
        return besInfoVO;
    }
}
